﻿namespace DatabaseDoc.Connectors.Sql
{
    using System;

    using Microsoft.SqlServer.Management.Common;
    using Microsoft.SqlServer.Management.Smo;

    public class SqlServerConnection : IDisposable
    {
        private ServerConnection serverConnection;

        /// <summary>
        /// Initializes a new instance of the <see cref="SqlServerConnection"/> class.
        /// </summary>
        /// <param name="serverName">Name of the server.</param>
        /// <param name="databaseName">Name of the database.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        public SqlServerConnection(string serverName, string databaseName = null, string userName = null, string password = null)
        {
            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                this.serverConnection = new ServerConnection(serverName);    
            }
            else
            {
                this.serverConnection = new ServerConnection(serverName, userName, password);
            }

            if (!string.IsNullOrWhiteSpace(databaseName))
            {
                this.serverConnection.DatabaseName = databaseName;
            }
                        
            this.Current = new Server(this.serverConnection);
        }

        /// <summary>
        /// Gets the current server instance.
        /// </summary>
        /// <value>The current server instance.</value>
        public Server Current { get; private set; }
        
        public void Dispose()
        {
            if (this.serverConnection != null)
            {
                this.serverConnection.Disconnect();
                this.serverConnection = null;
            }
        }
    }
}